import React, { Component } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Image, ScrollView, DeviceEventEmitter
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import DatePicker from 'react-native-datepicker';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import Upload from '../../../utils/Upload';
import Dictionary from '../../../utils/dictionary';
import { GLOBAL } from '../../../config/global';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import { enterpriseStyles } from '../_common/enterpriseStyle';
import { Common } from '../../../component/common/Common';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import ToastUtil from '../../../utils/toast';

const scale = GLOBAL.SCALE;
const scan = require('../../../imgs/global/scan.png');
const uploadPic = require('../../../imgs/store/upload.png');

const modalPicDelCfg = {
  visible: false,
  uri: null,
  delPress: () => { },
  picPress: () => { },
  fileId: '',
}
const fileIdObj = {};
let responseDataParams = {};
let qualificationTypeDefault = [{
  dictName: "危险化学品经营许可证",
  dictKey: 'QZ_001'
}, {
  dictName: "危险化学品生产单位登记证",
  dictKey: 'QZ_002'
}, {
  dictName: "危险化学品安全使用许可证",
  dictKey: 'QZ_003'
}, {
  dictName: "非药品类易制毒化学品经营备案证明",
  dictKey: 'QZ_004'
}, {
  dictName: "易制爆危险化学品从业单位备案证明",
  dictKey: 'QZ_005'
}, {
  dictName: "燃气经营许可证",
  dictKey: 'QZ_006'
}, {
  dictName: "成品油批发/零售许可证",
  dictKey: 'QZ_007'
}];

export class EnterpriseCreateQualificationInfo extends Component {

  static navigationOptions = ({ navigation }) => {
    const params = navigation.state.params || {};
    const { responseData } = params;
    responseDataParams = responseData || {};

    return {
      header: null,
      gesturesEnabled: false
    };
  };

  requesting;
  constructor(props) {
    super(props);
    this.state = {
      loadQualification: true,
      previewModalVisible: false,
      qualificationTypeList: [],
      qualificationTypeObj: {},
      loaded: false,
      labelShowObj: {

      },
      offsetY: 0
    }
    this.choice = props.navigation.state.params.choice || {};
    this.sendData = responseDataParams || {};
    this.sendData.step = 3;
    if (responseDataParams.companyInfoVO && responseDataParams.companyInfoVO.companyId) {
      this.companyId = responseDataParams.companyInfoVO.companyId;
    }

    this.selectPhotoTapped = this.selectPhotoTapped.bind(this);
    this.qualificationFileHandle = this.qualificationFileHandle.bind(this);

    this.requireQualification = this.props.navigation.state.params.requireQualification;

    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
        previewModalVisible: false,
      });
    }
    //要改
    modalPicDelCfg.delPress = () => {
      const { index, typeId } = this.curQualification;
      const { qualificationTypeObj } = this.state;
      let qualification = qualificationTypeObj[typeId];
      if (!qualification) {
        let qualification = {};
        modalPicDelCfg.visible = false;
        modalPicDelCfg.uri = null;
        qualification.uriList = [];
        this.setState({
          previewModalVisible: false,
          qualificationTypeObj,
        });
      } else {

        const { uriList } = qualification;
        modalPicDelCfg.visible = false;
        modalPicDelCfg.uri = null;

        qualification.uriList = uriList.splice(index, 1);
        qualification.uriList = uriList;
        qualificationTypeObj[typeId] = qualification;
        this.setState({
          previewModalVisible: false,
          qualificationTypeObj,
        });
      }

    }
    this.curQualification = {
      index: null
    }
  }

  async componentWillMount() {
    //资质类型
    const qualificationTypeObj = {};
    let qualificationTypes = await Dictionary.get("EC_QUALIFICATION_TYPE");
    if (!qualificationTypes || qualificationTypes.length <= 0) {
      qualificationTypes = qualificationTypeDefault;
    }
    const qualificationTypeList = qualificationTypes.map(item => {
      const { dictKey, dictName } = item;
      qualificationTypeObj[dictKey] = {
        name: dictName,
        uriList: [],
        expireDate: ''
      };

      this.setState({
        qualificationTypeObj
      });

      if (responseDataParams.qualificationList && responseDataParams.qualificationList.length > 0) {
        responseDataParams.qualificationList.map(item => {
          if (item.qualificationType == dictKey) {
            qualificationTypeObj[dictKey].expireDate = item.expireDate;
            this.setState({
              qualificationTypeObj,
            })

            if (item.qualificationAddress) {
              const qualificationArr = item.qualificationAddress.split(',');
              qualificationArr.map((id, index) => {
                this.loadedImgs(id, qualificationTypeObj[dictKey], dictKey);
              })
            }
          }
        })
      }

      return dictKey;
    });
    this.setState(
      {
        loadQualification: false,
        qualificationTypeList,
      }
    );
  }

  async loadedImgs(id, types, type) {
    const { qualificationTypeObj } = this.state;
    const fetchCreditFileAsync = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: id }, null, 30000);
    if (fetchCreditFileAsync) {
      let { image } = fetchCreditFileAsync;
      if (image && image.length) {
        types.uriList.push({
          uri: image,
          typeId: type,
        });
        fileIdObj[image] = id;
        qualificationTypeObj[type] = types;
      }
    } else {
      types.uriErrorList.push({
        uri: '../../../imgs/global/scan.png',
        typeId: type,
      });
      fileIdObj[scan] = id;
      qualificationTypeObj[type] = types;
    }


    this.setState({
      qualificationTypeObj,
    })
  }

  componentWillUnmount() {
    this.setState({
      loaded: false
    });
  }

	/**
 * 上传图片
 * @param {String} attachment 统一社会信用证文件 分类
 * @param {function} handle
 * @param {String} ocrType 分类
 */
  selectPhotoTapped(handle, ocrType, qualificationKey) {
    const options = {
      title: '请选择图片来源',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '相册图片',
      quality: 1,
      maxWidth: 1080,
      maxHeight: 1080,
      storageOptions: {
        skipBackup: true,
        // path: 'images'
      },
      mediaType: 'photo',
    };
    ImagePicker.showImagePicker(options, async (response) => {
      const { qualificationTypeObj, labelShowObj } = this.state;

      if (response.didCancel) {
        console.log('User cancelled photo picker');
        return;
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
        return;
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
        return;
      }
      else {
        if (qualificationTypeObj && qualificationTypeObj[qualificationKey] && qualificationTypeObj[qualificationKey].uriList) {
          qualificationTypeObj[qualificationKey].uriList.push({
            uri: response.uri,
            typeId: qualificationKey,
          });
          this.setState({
            qualificationTypeObj,
            loaded: true,
          });
        }
      }

      const uploadImgObj = {
        imgUrl: { uri: response.uri },
        url: API_GENERATE(API.IMG_UPLOAD),
      }
      if (ocrType && ocrType.length) {
        uploadImgObj.ocrType = ocrType;
        uploadImgObj.isOcr = 1;
      } else {
        uploadImgObj.isOcr = 0
      }

      let responseData = await Upload.uploadImg(uploadImgObj);
      labelShowObj[qualificationKey] = true;
      this.setState({
        labelShowObj
      });
      if (responseData) {
        if (handle && (typeof (handle) == 'function')) {
          responseData.uri = response.uri;
          handle(responseData, qualificationKey);
        }
      }
      this.setState({
        loaded: false
      });
    });
  }

  _setTimeCallback = (date, selectedTypeId) => {
    const { qualificationTypeObj } = this.state;
    qualificationTypeObj[selectedTypeId].expireDate = date;
    this.setState({
      qualificationTypeObj
    })
  }

  render() {
    let qualificationListView = null;
    const { qualificationTypeList, loadQualification, qualificationTypeObj, loaded, selectedTypeId } = this.state;
    const { productText } = this.props.navigation.state.params;

    if (!loadQualification) {
      qualificationListView = qualificationTypeList.map((typeId, index) => {
        const qualification = qualificationTypeObj[typeId] || {};
        const selectedTypeId = typeId;
        if (qualification) {
          const { name, uriList, expireDate } = qualification;
          const requireText = (this.requireQualification && this.requireQualification[typeId]) ? <Text style={enterpriseStyles.requireText}>*</Text> : null;
          // const leftImg = qualificationSource[i][dictKey] ? qualificationSource[i][dictKey] : uploadPic;

          const picViews = uriList.map((item, i) => {
            const { uri } = item;
            return (
              <TouchableOpacity key={i} style={enterpriseStyles.attachment} onPress={() => {

                this.curQualification = {
                  index: i,
                  typeId
                };
                modalPicDelCfg.visible = true;
                modalPicDelCfg.uri = uri;
                modalPicDelCfg.fileId = fileIdObj[uri];
                this.setState({
                  ls: true
                })
              }} activeOpacity={0.5} >
                <Image source={item} style={enterpriseStyles.cover} />
              </TouchableOpacity>
            )
          });

          return (
            <View key={typeId}>
              <Text style={enterpriseStyles.lableText}>{name}{requireText}</Text>
              <View style={enterpriseStyles.attachmentRow}>
                {picViews}
                <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
                  this.selectPhotoTapped(this.qualificationFileHandle, 0, typeId);
                }} activeOpacity={0.5} >
                  <Image source={uploadPic} style={enterpriseStyles.cover} />
                </TouchableOpacity>
              </View>
              <View style={enterpriseStyles.selectContainer}>
                <Text style={[enterpriseStyles.lableText, { marginRight: 12 * scale }]}>有效期至</Text>
                <DatePicker
                  style={{ width: 200 }}
                  date={expireDate}
                  mode="date"
                  placeholder="请选择"
                  format="YYYY-MM-DD"
                  minDate={new Date()}
                  maxDate="2100-12-01"
                  confirmBtnText="确认"
                  cancelBtnText="取消"
                  customStyles={{
                    dateIcon: {
                      opacity: 0,
                      width: 0
                    },
                    dateInput: {
                      marginLeft: 36,
                      borderWidth: 0
                    },
                    placeholderText: {
                      fontSize: 14 * scale,
                      color: '#404040'
                    }
                  }}
                  onDateChange={(date) => { this._setTimeCallback(date, selectedTypeId); }}
                />
              </View>
              {
                index !== qualificationTypeList.length ?
                  <View style={enterpriseStyles.attachmentborder}></View>
                  : null
              }
            </View>
          );
        }
      });
    }

    return (
      <ScrollView style={styles.scrollView} onScroll={(e) => {
        let offsetY = e.nativeEvent.contentOffset.y; //滑动距离
        this.setState({
          offsetY
        })
      }}>
        <View style={styles.container}>
          <ModalPicDelComponent {...modalPicDelCfg} />
          <View style={styles.wrap}>
            <Common type="headLeft" onPress={() => {
              const { navigate } = this.props.navigation;
              navigate('EnterpriseCreateAdditionInfo', {
                responseData: this.sendData
              });
            }} ifHiddenTitle={true} imgStyle={{ marginLeft: 0, marginTop: GLOBAL.IS_IPHONEX ? 42 * scale : 18 * scale }} />
            <Text style={enterpriseStyles.titleText}>企业信息</Text>
            <View>
              <Text style={enterpriseStyles.lableText}>商品</Text>
              <Text style={styles.productText}>{productText}</Text>
              <Text style={[styles.productText, { color: 'red' }]}>上传格式支持jpg、png等图片格式</Text>
            </View>

            {qualificationListView}

            <View style={enterpriseStyles.footBtnCell}>
              <TouchableOpacity style={[enterpriseStyles.footBtn, { flex: 1 }]} onPress={() => {
                const { navigate } = this.props.navigation;
                navigate('EnterpriseCreateAdditionInfo', {
                  responseData: this.sendData,
                  bankList: null,
                  addressList: null,
                  contactData: null,
                  invoiceData: null,
                });
              }} activeOpacity={0.5} >
                <Text style={enterpriseStyles.footBtnText}>上一步</Text>
              </TouchableOpacity>
              <View style={enterpriseStyles.footSaveBtn}>
                <TouchableOpacity style={enterpriseStyles.footSaveBtnBtn} onPress={() => this._didPressNextBtn(3)} activeOpacity={0.5} >
                  <Text style={enterpriseStyles.footSaveBtnText}>保存</Text>
                </TouchableOpacity>
              </View>
              <TouchableOpacity style={[enterpriseStyles.footBtn, { flex: 1 }]} onPress={() => this._didPressNextBtn(4)} activeOpacity={0.5} >
                <Text style={enterpriseStyles.footBtnText}>提交</Text>
              </TouchableOpacity>
            </View>

          </View>
        </View>
        {
          this.state.loaded ?
            <View style={{ position: 'absolute', height: GLOBAL.SCREEN_HEIGHT, width: GLOBAL.SCREEN_WIDTH, top: this.state.offsetY }}>
              <PageStatusIndex status='loading' />
            </View>
            : null
        }
      </ScrollView>
    )
  }

  /**
   * 资质图片上传后
   * @param object data 
   * @param {String} qualificationKey 
   */
  qualificationFileHandle(data, qualificationKey) {
    const { fileId, uri } = data;
    fileIdObj[uri] = fileId;
  }


  async _didPressNextBtn(step) {
    const { qualificationTypeList, qualificationTypeObj } = this.state;
    const qualificationList = [];
    const qualificationMsg = [];
    let qualificationEndDateMsg = '';
    this.sendData.step = step;
    qualificationTypeList.forEach((typeId, index) => {
      const qualification = qualificationTypeObj[typeId];
      const { name, uriList, expireDate } = qualification;
      if (this.requireQualification[typeId]) {
        if (!uriList || !uriList.length) {
          qualificationMsg.push('请上传资质:' + name);
        }
      }

      let a = ''; let item; let paramsId;
      uriList.forEach((uriListitem, i) => {
        if (uriListitem) {
          const fildId = fileIdObj[uriListitem.uri];
          a += (i === 0 ? '' : ',') + fildId;

          if (responseDataParams.qualificationList && responseDataParams.qualificationList.length > 0) {
            responseDataParams.qualificationList.map((Addr, i) => {
              if (Addr.qualificationType == typeId && Addr.qualificationAddress) {
                paramsId = Addr.id;
              }
            })
          }

          item = {
            qualificationType: typeId,
            companyId: this.companyId,
            qualificationAddress: a,
            id: paramsId,
            expireDate
          }

        }
      })

      if (item) {
        qualificationList.push(item);
      }
    });

    this.sendData.qualificationList = qualificationList;
    if (qualificationMsg.length) {
      ToastUtil.showWarning(qualificationMsg);
      return;
    }
    if (qualificationList.some(item => {
      qualificationEndDateMsg = qualificationTypeObj[item.qualificationType].name
      return !item.expireDate;
    })) {
      ToastUtil.showWarning('请选择' + qualificationEndDateMsg + '有效截止日期');
      return;
    }

    this.sendData.corpId = this.choice.corpId;
    if (this.requesting) return;
    this.setState({ loaded: true });
    this.requesting = true;
    const responseData = await HTTP.POST(API_GENERATE(API.ADD_APPLY_COMPANY), this.sendData);

    this.setState({
      loaded: false
    })

    const msg1 = step === 3 ? '您添加的企业已保存' : '您添加的企业已提交';
    const msg2 = step === 3 ? '可在到草稿中查看' : '请耐心等待审核';
    const page = step === 3 ? '1' : '2';

    if (responseData) {
      ToastUtil.showSuccess(msg1 + msg2).then(() => { this._goBack(page); })
    } else {
      this.requesting = false;
    }

  }

  // 返回上一个页面
  _goBack = (page) => {
    this.requesting = false;
    const { navigate } = this.props.navigation;
    DeviceEventEmitter.emit('refreshPage', page);
    navigate('CustomerIndexPage');
  }

}

const styles = StyleSheet.create({
  scrollView: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container: {
    flex: 1,
    alignItems: 'center',
  },
  wrap: {
    width: 345 * scale,
  },
  closeTextCell: {
    position: 'absolute',
    left: 8,
    top: 0,
  },
  productText: {
    fontSize: 14 * scale,
    color: '#404040',
    marginBottom: 8 * scale,
    paddingTop: 14 * scale,
    lineHeight: 14 * scale,
  },
  ocrWrap: {
    width: 375 * scale,
    height: GLOBAL.SCREEN_HEIGHT,
    backgroundColor: 'rgba(0, 0, 0, 0)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadedCell: {
    width: 75 * scale,
    height: 75 * scale,
    backgroundColor: 'rgba(0, 0, 0, .5)',
    borderRadius: 7,
    justifyContent: 'center',
    alignItems: 'center',
  },
  endDate: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
})